% Assumes that groups.dat defines the areas you want to see.
% Must be in the directory in which the simulation was run.
% function plot_net_area(area_name, type_name, num_procs);
% plot_syn_diff_retrograde('S1','p23',5,1,.3,8);view(0,90);
function plot_syn_diff_retrograde(area_name, type_name, tracer_x_mm, tracer_y_mm, tracer_spread_mm, num_procs, thresh);

connectfile='connect.dat';
[a b c d e f g h]=textread(connectfile,'%f%f%f%f%f%f%f%f%*[^\n]','delimiter','\t');
connect=[a b h];


read_groups; % Assumes groups.dat has the neural area data

if nargin < 7
    thresh = 0.2;
end

index = [];
for i=1:length(areas)
    if strcmp( deblank(areas{i}), area_name) && strcmp( type_name, deblank(celltype{i})) 
        index = i
        break;
    end
end
if isempty(index)
    disp([area_name ' ' type_name ' is not in groups.dat.']);
    return;
end

%%  For each file, find the cells within retrograde tracer spread.
figure(1)
hold off
num_procs
for i=(0:num_procs:num_procs-1) %num_procs-1)
    i
    neuron_num = (neuron_id(index,1)+i):num_procs:neuron_id(index,2)
    
    
    % Find the neurons within the tracer spread.
    ind = find( (a(neuron_num'+1)-tracer_x_mm).^2 + ( b(neuron_num'+1)-tracer_y_mm).^2 < tracer_spread_mm^2 )
    
    if( isempty(ind) )
        continue;
    end
    neuron_num = neuron_num(ind);
    
    synfile = [ num2str(mod(neuron_num(1),num_procs)) '-' num2str(neuron_id(end,end)+1) '.syn'];
    synfile2 = [ num2str(mod(neuron_num(1),num_procs)) '-' num2str(neuron_id(end,end)+1) 'final.syn'];
    
    X=load(synfile);
    X1=load(synfile2);
    
    
    
    for kk=1:length(neuron_num)
        ind=find(X(:,1)==neuron_num(kk));
        
        syn_diff=X1(ind,3)-X(ind,3);
        
        length(ind)
        for ii=1:length(ind)
            xyz0=connect(X(ind(ii),2)+1,:);
            if syn_diff(ii)>thresh
                plot3(xyz0(:,1),xyz0(:,2),xyz0(:,3)+1,'r.');
            elseif syn_diff(ii)<-thresh
                plot3(xyz0(:,1),xyz0(:,2),xyz0(:,3)+1,'g.');
            else
                plot3(xyz0(:,1),xyz0(:,2),xyz0(:,3)+1,'y.');
            end
            hold on
        end;
        xyz1=connect(X(ind(1),1)+1,:);
        plot3(xyz1(:,1),xyz1(:,2),xyz1(:,3)+1,'k*');
        
        clear ind
    end;
    
end

title(['Retrograde tracer from cells marked with * in group ',area_name ' ' type_name ]);



